/**
 * 弹窗form
 * @Author: linzy
 * @Date: 2022-06-23
 * @function useModalForm
 * @param {array} modalItems - 弹窗表单项数组
 * @param {object} values - 表单值对象
 * @param {function} onSubmit - 表单提交时触发
 * @param {object} ref - 表单form ref对象
 * @param {boolean} loading - 提交时loading
 * @param {string} title - 弹窗标题
 * @returns [ModalForm, modalFormProps, setVisible, transformDetail]
 * @example
const modalFormRef = useRef();
const modalItems = [
  { label: '名称', name: 'title', type: 'input', required: true },
  { label: "图片", name: "img", type: "upload" },
  { label: "下拉", type: "select", name: "set", options: [],
    map: ["id", "name"]
  },
];
const [ModalForm, modalFormProps, setVisible, transformDetail] = useModalForm({
  modalItems,
  ref: modalFormRef,
  onSubmit(values) {
    // ajax
  },
});
<ModalForm {...modalFormProps} title="新建xxx" />

*/
import { useRef } from "react";
import { useForm, useModal } from "@/hooks";
import { transformValues, getValidNameList } from "@/hooks/tools";

export default props => {
  const formRef = useRef();
  const {
    modalItems = [],
    values,
    onSubmit,
    ref,
    loading,
    title,
    disabled,
    useFormProps
  } = props;
  const [Modal, modalProps, setVisible] = useModal();
  const [Form, formProps, transformDetail] = useForm({
    formItems: modalItems,
    buttons: false,
    values,
    buttonsFormItemProps: {
      style: { textAlign: "right", marginBottom: 0 }
    },
    disabled,
    ...useFormProps
  });
  ref ? (formProps.ref = ref) : (formProps.ref = formRef);
  modalProps.children = <Form {...formProps} />;
  modalProps.onCancel = () => {
    props.onCancel && props.onCancel();
    formProps.ref.current && formProps.ref.current.resetFields();
    setVisible(false);
  };
  modalProps.confirmLoading = loading;
  modalProps.forceRender = true;
  title && (modalProps.title = title);
  modalProps.onOk = () => {
    var validNameList = getValidNameList(modalItems);
    formProps.ref.current.validateFieldsAndScroll(
      validNameList,
      (err, values) => {
        if (!err) {
          const newValues =
            modalItems.length > 0
              ? transformValues(values, modalItems)
              : values;
          onSubmit && onSubmit(newValues);
        } else {
          var ele = document.querySelector(
            ".ant-modal-body .ant-form-item-control.has-error"
          );
          ele.scrollIntoView({
            behavior: "smooth"
          });
        }
      }
    );
  };
  function setVisibleRewrite(bool) {
    setVisible(bool);
    if (bool === false) {
      formProps.ref.current && formProps.ref.current.resetFields();
    }
  }
  disabled &&
    (modalProps.okButtonProps = {
      disabled: true
    });
  return [Modal, modalProps, setVisibleRewrite, transformDetail];
};
